{
  "nbformat": 4,
  "nbformat_minor": 0,
  "metadata": {
    "colab": {
      "provenance": []
    },
    "kernelspec": {
      "name": "python3",
      "display_name": "Python 3"
    },
    "language_info": {
      "name": "python"
    }
  },
  "cells": [
    {
      "cell_type": "markdown",
      "source": [
        "<a href=\"https://colab.research.google.com/drive/1T-YJ2YVjH0hzA3QBO4Wg15SSrXn6Tv3c?usp=sharing\" target=\"_parent\"><img src=\"https://colab.research.google.com/assets/colab-badge.svg\" alt=\"Open In Colab\"></a>\n",
        "\n",
        "### 🔄 Self-Consistency - Prompt Engineering\n",
        "\n",
        "Self-Consistency is a method to improve the reliability of language model outputs.\n",
        "\n",
        "### Key points:\n",
        "\n",
        "* 🔑 **Core concept:** Generate multiple independent solutions and select the most consistent one.\n",
        "\n",
        "* ⚙️ **Process:**\n",
        "  * Prompt the model multiple times for the same task\n",
        "  * Collect various reasoning paths and answers\n",
        "  * Choose the most common or consistent answer\n",
        "\n",
        "* 🌟 **Advantages:**\n",
        "  * Improves accuracy, especially for complex tasks\n",
        "  * Reduces impact of occasional errors or biases\n",
        "\n",
        "* 💼 **Applications:** Mathematical problem-solving, logical reasoning, decision-making.\n",
        "\n",
        "* 🚀 **Implementation:**\n",
        "  * Use temperature settings to introduce variability\n",
        "  * Prompt for full reasoning chains, not just final answers\n",
        "\n",
        "* **Evaluation:** Can use voting mechanisms or more sophisticated consistency measures.\n",
        "\n",
        "* ⚖️ **Challenges:**\n",
        "  * Increased computational cost\n",
        "  * Handling genuinely ambiguous problems\n",
        "\n",
        "* 🔄 **Variations:** Can be combined with other techniques like Chain of Thought or Tree of Thoughts."
      ],
      "metadata": {
        "id": "Y2eqHW0TK87s"
      }
    },
    {
      "cell_type": "code",
      "source": [
        "!pip install -q -U langchain-groq==0.2.4"
      ],
      "metadata": {
        "colab": {
          "base_uri": "https://localhost:8080/"
        },
        "id": "KI4D1HL-LKaP",
        "outputId": "fe751948-cddc-4c7a-f076-39873cfa3389"
      },
      "execution_count": 1,
      "outputs": [
        {
          "output_type": "stream",
          "name": "stdout",
          "text": [
            "\u001b[?25l   \u001b[90m━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━\u001b[0m \u001b[32m0.0/121.9 kB\u001b[0m \u001b[31m?\u001b[0m eta \u001b[36m-:--:--\u001b[0m\r\u001b[2K   \u001b[90m━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━\u001b[0m \u001b[32m121.9/121.9 kB\u001b[0m \u001b[31m5.4 MB/s\u001b[0m eta \u001b[36m0:00:00\u001b[0m\n",
            "\u001b[?25h"
          ]
        }
      ]
    },
    {
      "cell_type": "code",
      "source": [
        "from langchain_groq import ChatGroq\n",
        "from langchain.prompts import ChatPromptTemplate"
      ],
      "metadata": {
        "id": "dfHHptAFLMwj"
      },
      "execution_count": 2,
      "outputs": []
    },
    {
      "cell_type": "code",
      "source": [
        "import os\n",
        "import getpass"
      ],
      "metadata": {
        "id": "eZJGDTIMLOnP"
      },
      "execution_count": 3,
      "outputs": []
    },
    {
      "cell_type": "markdown",
      "source": [
        "### 🔑 Provide Groq API Key\n",
        "\n",
        "- [Groq API Key](https://console.groq.com/keys)\n",
        "\n"
      ],
      "metadata": {
        "id": "rQrlkg_bLRZp"
      }
    },
    {
      "cell_type": "code",
      "source": [
        "os.environ[\"GROQ_API_KEY\"] = getpass.getpass()"
      ],
      "metadata": {
        "colab": {
          "base_uri": "https://localhost:8080/"
        },
        "id": "XI8sLK8uLTht",
        "outputId": "c10783fb-df26-42fb-bd37-237a700a369c"
      },
      "execution_count": 4,
      "outputs": [
        {
          "name": "stdout",
          "output_type": "stream",
          "text": [
            "··········\n"
          ]
        }
      ]
    },
    {
      "cell_type": "code",
      "source": [
        "llm = ChatGroq(\n",
        "    model=\"llama3-8b-8192\",\n",
        "    temperature=0.5\n",
        ")"
      ],
      "metadata": {
        "id": "0os_AIehLVh1"
      },
      "execution_count": 5,
      "outputs": []
    },
    {
      "cell_type": "code",
      "source": [
        "self_consistency_prompt = ChatPromptTemplate.from_messages(\n",
        "    [\n",
        "        (\"system\", \"You are an AI that can solve problems using multiple approaches.\"),\n",
        "        (\"human\", \"Solve this problem using three different methods: {input}\"),\n",
        "        ]\n",
        ")\n",
        "\n",
        "chain = self_consistency_prompt | llm"
      ],
      "metadata": {
        "id": "FToKQB7jLBYD"
      },
      "execution_count": 6,
      "outputs": []
    },
    {
      "cell_type": "code",
      "source": [
        "problem =  \"What is the volume of a cube with side length 4cm?\"\n",
        "response = chain.invoke({\"input\": problem})\n",
        "print(response.content)"
      ],
      "metadata": {
        "colab": {
          "base_uri": "https://localhost:8080/"
        },
        "id": "0PWEvnMyLZSb",
        "outputId": "d3894a38-9144-42a1-d36e-7c8f83b52cd8"
      },
      "execution_count": 7,
      "outputs": [
        {
          "output_type": "stream",
          "name": "stdout",
          "text": [
            "Here are three different methods to solve the problem:\n",
            "\n",
            "**Method 1: Formula**\n",
            "\n",
            "The formula to calculate the volume of a cube is:\n",
            "\n",
            "Volume = Side length × Side length × Side length\n",
            "\n",
            "In this case, the side length is 4 cm, so:\n",
            "\n",
            "Volume = 4 cm × 4 cm × 4 cm\n",
            "= 64 cubic centimeters (or 64 cm³)\n",
            "\n",
            "**Method 2: Dimensional Analysis**\n",
            "\n",
            "We can use dimensional analysis to solve this problem. The volume of a cube is measured in cubic units (e.g., cm³), and the side length is measured in linear units (e.g., cm). We can set up a conversion factor to relate the side length to the volume:\n",
            "\n",
            "1 cm × 1 cm × 1 cm = 1 cm³\n",
            "\n",
            "Now, we can multiply the side length by itself three times to get the volume:\n",
            "\n",
            "4 cm × 4 cm × 4 cm = 4 × 4 × 4 cm³\n",
            "= 64 cm³\n",
            "\n",
            "**Method 3: Visualization**\n",
            "\n",
            "We can visualize the cube and calculate its volume by counting the number of small cubes that fit inside it. Each small cube has a volume of 1 cubic centimeter (1 cm³). Since the side length of the large cube is 4 cm, we can imagine it as a stack of 4 small cubes along each edge. Therefore, the volume of the large cube is:\n",
            "\n",
            "4 small cubes × 4 small cubes × 4 small cubes\n",
            "= 64 small cubes\n",
            "= 64 cm³\n",
            "\n",
            "All three methods yield the same answer: the volume of the cube with side length 4 cm is 64 cubic centimeters (64 cm³).\n"
          ]
        }
      ]
    },
    {
      "cell_type": "code",
      "source": [],
      "metadata": {
        "id": "ja7ZCUY2MJT2"
      },
      "execution_count": null,
      "outputs": []
    }
  ]
}